package com.boruan.shengtangfeng.core.utils;

import java.io.File;

import com.boruan.shengtangfeng.core.dao.IVideoDao;
import com.boruan.shengtangfeng.core.entity.Video;

import lombok.extern.slf4j.Slf4j;
import ws.schild.jave.MultimediaInfo;
import ws.schild.jave.MultimediaObject;

@Slf4j
public class CalculateVideoDurationThread extends Thread{
	private IVideoDao videoDao;
	public CalculateVideoDurationThread(){
	}
	public CalculateVideoDurationThread(IVideoDao videoDao){
		this.videoDao=videoDao;
	}
	public void run() {
		try {
			while(Global.VIDEO_THREAD_RUN){
				int count = calculateDuration();
				//如果没有需要处理的日志，线程休息，避免死循环
				if (count<=0) {
					try {
//						logger.debug("登录日志队列为空，休眠"+Global.LOG_THREAD_SLEEP_TIME);
						Thread.sleep(Global.VIDEO_THREAD_SLEEP_TIME);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 保存搜索日志
	 * @return 本次处理记录条数
	 */
	private int calculateDuration(){
		int count=0;
		try {
			if (Global.videoQueue!=null && !Global.videoQueue.isEmpty()) {
			    Video video=null;
				while ((video=Global.videoQueue.poll()) != null) {
					Video update=new Video();
					update.setId(video.getId());
					Integer duration=VideoUtil.getDuration(video.getContent());
					if(duration==null) {
					    //出错直接设为0，防止重复读取浪费资源
					    duration=0;
					}
					update.setDuration(duration);
					videoDao.updateTemplateById(update);
					count++;
				}
				//插入数据库
				log.info("视频时长计算写入数据库条数:{}",count);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return count;
	}
}
